import random
import string
import smtplib
import json
import re
from urllib.request import urlopen
from email.mime.text import MIMEText
from django.conf import settings
from django.template.loader import render_to_string


def generate_captcha():
    return ''.join(random.sample(string.digits, 4))


def get_random_avatar():
    """
    See: http://api.btstu.cn/doc/sjtx.php
    """
    response = urlopen(
        'http://api.btstu.cn/sjtx/api.php?lx=c1&format=json').readlines()[0]
    return json.loads(response)['imgurl']


def is_email_valid(email: str) -> bool:
    return re.match(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", email)


def send_email(recipient, captcha=None):

    html_msg = render_to_string('user/email.html', {'captcha': captcha})

    sender = settings.EMAIL_HOST_USER
    msg = MIMEText(html_msg, 'html')
    msg['subject'] = '欢迎注册LookeLooke.com'
    msg['from'] = f'LookeLooke.com {sender}'
    msg['to'] = recipient
    s = smtplib.SMTP_SSL(settings.EMAIL_HOST, 465)
    print(settings.EMAIL_HOST_PASSWORD)
    s.login(sender, settings.EMAIL_HOST_PASSWORD)
    s.sendmail(sender, recipient, msg.as_string().encode("utf-8"))
    return 'Success'
